#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/syscall.h>
#include <string.h>

int main()
{
    pid_t result;
    int r_num;
    int pipe_fd[2]; //存储文件描述符
    char buf_r[128];
    memset(buf_r, 0, sizeof(buf_r)); //初始化缓冲区
    if (pipe(pipe_fd) < 0)
    {
        printf("创建管道失败.\n");
        return -1;
    }
    result = fork();
    if (result < 0)
    {
        printf("子进程派生失败.\n");
        exit;
    }
    else if (result == 0)
    {
        //子进程
        close(pipe_fd[1]);
        sleep(1);
        if ((r_num = read(pipe_fd[0], buf_r, 128)) > 0)
        {
            printf("子进程从管道读取%d个字符，读取的字符串是：%s\n", r_num, buf_r);
        }
        close(pipe_fd[0]);
        exit(0);
    }
    else
    {
        //父进程
        close(pipe_fd[0]);
        if (write(pipe_fd[1], "Hello World! ", 13) != -1)
        {
            printf("父进程向管道写入：Hello World!\n");
        }
        if (write(pipe_fd[1], "Welcome to pipe.", 16) != -1)
        {
            printf("父进程向管道写入：Welcome to pipe.\n");
        }
        close(pipe_fd[1]);
        waitpid(result, NULL, 0); //死等子进程结束
        exit(0);
    }
    return 0;
}